package com.jcompressor.preferences;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class PropertyExpander {
	
	private final Map<String, String> properties;
	private final String pre;
	private final String post;
	private final Map<Object, Object> cache;
	
	public PropertyExpander(final Map<String, String> properties, final String pre, final String post) {
		this.properties = properties;
		this.pre = pre;
		this.post = post;
		this.cache = new HashMap<Object, Object>();
	}
	
	public void clearCache() {
		this.cache.clear();
	}
	
	public String expandProperties(final String source) {
		String result = (String)this.cache.get(source);
		if (StringUtils.isEmpty(source) || StringUtils.isNotBlank(result)) {
			return result;
		}
		
		int firstIndex = StringUtils.indexOf(source, this.pre);
		if (firstIndex == -1) {
			return source;
		}
		
		final StringBuffer buffer = new StringBuffer(source);
		while (firstIndex > -1) {
			final int lastIndex = StringUtils.indexOf(buffer.toString(), this.post);
			final int start = (firstIndex + this.pre.length());
			if (firstIndex == 0) {
				final String key = StringUtils.substring(buffer.toString(), start, (start + lastIndex - this.pre.length()));
				if (this.properties.containsKey(key)) {
					buffer.replace(firstIndex, (firstIndex + lastIndex + 1), this.properties.get(key));
				}
				else {
					break;
				}
			}
			else {
				final String key = StringUtils.substring(buffer.toString(), start, lastIndex);
				if (this.properties.containsKey(key)) {
					buffer.replace(firstIndex, (lastIndex + 1), this.properties.get(key));
				}
				else {
					break;
				}
			}
			
			firstIndex = StringUtils.indexOf(buffer.toString(), this.pre);
		}
		
		result = buffer.toString();
		this.cache.put(source, result);
		
		return result;
	}
	
}